package com.monkeygroup.mygoplus.ecchat.ui.group;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.monkeygroup.mygoplus.MyGoApplication;
import com.monkeygroup.mygoplus.R;
import com.monkeygroup.mygoplus.base.BaseActivity;
import com.monkeygroup.mygoplus.common.utils.VilidateUtil;
import com.monkeygroup.mygoplus.ecchat.common.CCPAppManager;
import com.monkeygroup.mygoplus.ecchat.common.utils.ToastUtil;
import com.monkeygroup.mygoplus.ecchat.storage.GroupSqlManager;
import com.monkeygroup.mygoplus.ecchat.ui.SDKCoreHelper;
import com.monkeygroup.mygoplus.ecchat.ui.chatting.GlobalConstant;
import com.monkeygroup.mygoplus.ecchat.ui.contact.adapter.ChooseMemberAdatper;
import com.monkeygroup.mygoplus.ecchat.ui.contact.adapter.ChoosedMemberRecyclerAdapter;
import com.monkeygroup.mygoplus.ecchat.ui.contact.entity.ContactMemberDTO;
import com.monkeygroup.mygoplus.http.HttpModel;
import com.monkeygroup.mygoplus.http.RequestUrl;
import com.monkeygroup.mygoplus.view.home.activity.MainActivity;
import com.yuntongxun.ecsdk.ECError;
import com.yuntongxun.ecsdk.ECGroupManager;
import com.yuntongxun.ecsdk.SdkErrorCode;
import com.yuntongxun.ecsdk.im.ECGroup;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/6/29.
 */
public class InviteGroupMembers extends BaseActivity implements View.OnClickListener,
        ECGroupManager.OnCreateGroupListener,
        GroupMemberService.OnSynsGroupMemberListener {
    private ListView contact_choose_list_view;
    private RecyclerView choose_member_recycler;
    private LinearLayoutManager layoutManager;
    private ChoosedMemberRecyclerAdapter recyclerAdapter;
    private List<ContactMemberDTO> chooseFriendList = new ArrayList<>();
    private List<ContactMemberDTO> choosedList = new ArrayList<>();
    private ChooseMemberAdatper adatper;
    private final String TAG = "InviteContactActivity";

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_invite_group_member);
    }

    @Override
    public void initView() {
        contact_choose_list_view = (ListView) findViewById(R.id.contact_choose_list_view);
        choose_member_recycler = (RecyclerView) findViewById(R.id.choose_member_recycler);
        layoutManager = new LinearLayoutManager(InviteGroupMembers.this, LinearLayoutManager.HORIZONTAL, false);
        choose_member_recycler.setLayoutManager(layoutManager);
    }

    @Override
    public void setListener() {
        findViewById(R.id.layout_back).setOnClickListener(this);
        findViewById(R.id.layout_shortcut).setOnClickListener(this);

    }

    @Override
    public void doEvent() {
        String friendId = getIntent().getExtras().getString("friendid");

        Map<String, ContactMemberDTO> members = MyGoApplication.getContacts();
        if (members.containsKey(friendId)) {
            choosedList.add(members.get(friendId));
        }

        initAdapter();

        if (MyGoApplication.getContacts() != null && MyGoApplication.getContacts().size() > 0) {
            chooseFriendList.clear();
            chooseFriendList.addAll(MyGoApplication.getContacts().values());
            adatper.notifyDataSetChanged();
        } else {
            doAllContact();
        }
    }

    private void initAdapter() {
        adatper = new ChooseMemberAdatper(InviteGroupMembers.this, chooseFriendList, new ChooseMemberAdatper.OnChooseItemClickListener() {
            @Override
            public void onChooseClick(int position, boolean flag) {
                refreshChooseData(position, flag);
            }
        });
        contact_choose_list_view.setAdapter(adatper);

        recyclerAdapter = new ChoosedMemberRecyclerAdapter(InviteGroupMembers.this, choosedList);
        choose_member_recycler.setAdapter(recyclerAdapter);
    }

    private void refreshChooseData(int position, boolean flag) {
        if (flag) {
            for (int i = 0; i < choosedList.size(); i++) {
                if (choosedList.get(i).getId().equals(chooseFriendList.get(position).getId())) {
                    return;
                }
            }
            choosedList.add(chooseFriendList.get(position));
        } else {
            for (int i = 0; i < choosedList.size(); i++) {
                if (choosedList.get(i).getId().equals(chooseFriendList.get(position).getId())) {
                    choosedList.remove(i);
                    break;
                }
            }
        }
        recyclerAdapter.notifyDataSetChanged();
    }

    private void setFriendsData(List<Map<String, String>> list) {
        List<ContactMemberDTO> friendList = new ArrayList<>();
        for (Map<String, String> item : list) {
            ContactMemberDTO memberDTO = new ContactMemberDTO();
            if (item.get("username") != null && !item.get("username").equals("")) {
                memberDTO.setName((String) item.get("username"));
            } else if (item.get("userID") != null && !item.get("userID").equals("")) {
                memberDTO.setName((String) item.get("userID"));
            } else {
                memberDTO.setName((String) item.get("mobile"));
            }

            memberDTO.setId((String) item.get("mobile"));
            memberDTO.setHeadUrl((String) item.get("headIcon"));
            memberDTO.setStatus(item.get("status"));
            memberDTO.setEmail(item.get("email"));
            memberDTO.setIsOffice(item.get("isOffice"));
            memberDTO.setNotification(item.get("notification"));
            memberDTO.setRemark(item.get("remark"));
            friendList.add(memberDTO);
        }

        chooseFriendList.clear();
        chooseFriendList.addAll(friendList);
        adatper.notifyDataSetChanged();

        Map<String, ContactMemberDTO> friends = new HashMap<>();
        for (ContactMemberDTO memberDTO : friendList) {
            friends.put(memberDTO.getId(), memberDTO);
        }
        MyGoApplication.setContacts(friends);
    }

    private void doAllContact() {
        if (MyGoApplication.myECUserid.equals(""))
            return;

        String requestUrl = RequestUrl.baseUrl + RequestUrl.requestAllContact;
        HttpModel httpModel = new HttpModel(requestUrl, getParams(), new HttpModel.SimpleOnHttpRequestListener() {
            @Override
            public void onRequestFinished(int resultCode, String resultMsg, Object data) {
                if (VilidateUtil.isSuccess(resultCode)) {
                    Map<String, Object> map = (Map) data;
                    List<Map<String, String>> list = (ArrayList) map.get("friends");
                    setFriendsData(list);

                } else {
                    Toast.makeText(InviteGroupMembers.this, resultMsg, Toast.LENGTH_SHORT).show();
                }
            }
        }, true);

        httpModel.startRequest();
    }

    private Map<String, String> getParams() {
        Map<String, String> params = new HashMap<>();
        params.put("mobile", MyGoApplication.myECUserid);

        return params;
    }

    private String getGroupName() {
        String groupName = MyGoApplication.myNickname + "、";

        int size = choosedList.size() > 20 ? 20 : choosedList.size();
        for (int i = 0; i < size; i++) {
            if (choosedList.get(i).getName() != null && !choosedList.get(i).getName().equals("")) {
                groupName += choosedList.get(i).getName();
                if (i != (size - 1)) {
                    groupName += "、";
                }
            }
        }

        return groupName.length() > 50 ? groupName.substring(0, 50) : groupName;
    }

    private ArrayList<String> getChooseList() {
        ArrayList<String> list = new ArrayList<>();
        for (ContactMemberDTO memberDTO : choosedList) {
            list.add(memberDTO.getId());
        }

        return list;
    }

    private void CreateGroupWithInviteMembers() {
        ECGroupManager ecGroupManager = SDKCoreHelper.getECGroupManager();
        if (ecGroupManager == null) {
            return;
        }

        // 调用API创建群组、处理创建群组接口回调
        ECGroup group = getGroup();
        ecGroupManager.createGroup(group, this);
    }

    /**
     * 创建群组参数
     *
     * @return
     */
    private ECGroup getGroup() {
        ECGroup group = new ECGroup();
        // 设置群组名称
        String groupName = getGroupName();
        group.setName(groupName);
        // 设置群组公告
        group.setDeclare("無");
        // 临时群组（100人）
        group.setScope(ECGroup.Scope.TEMP);
        // 群组验证权限，不用驗證
        group.setPermission(ECGroup.Permission.AUTO_JOIN);
        // 设置群组创建者
        group.setOwner(CCPAppManager.getClientUser().getUserId());
//        group.setProvince("");
//        group.setCity("");

//        group.setGroupType();
        group.setIsDiscuss(true);

        return group;
    }

    @Override
    protected void onResume() {
        super.onResume();
        GroupMemberService.addListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.layout_back:
                finish();
                break;
            case R.id.layout_shortcut:
                if (choosedList.size() < 1) {
                    ToastUtil.showMessage("請至少選擇1位好友！");
                    return;
                }

                CreateGroupWithInviteMembers();
                break;
            default:
                break;
        }
    }

    @Override
    public void onCreateGroupComplete(ECError error, ECGroup group) {
        if (error.errorCode == SdkErrorCode.REQUEST_SUCCESS) {
            // 创建的群组实例化到数据库
            // 其他的页面跳转逻辑
            group.setIsNotice(false);
            GroupSqlManager.insertGroup(group, true, false, true);

            int size = choosedList.size();
            String members[] = new String[size];
            String reason = MyGoApplication.myNickname + "邀請您加入群聊";

            GroupMemberService.inviteMembers(group.getGroupId(), reason,
                    ECGroupManager.InvitationMode.FORCE_PULL, getChooseList().toArray(members));
        } else {
            ToastUtil.showMessage("創建群組失敗");
        }
    }

    @Override
    public void onSynsGroupMember(String groupId) {
        Intent intent = new Intent(InviteGroupMembers.this, MainActivity.class);
        intent.setAction(GlobalConstant.ACTION_CREATE_ENTER_GROUP);
        intent.putExtra("id", groupId);
        intent.putExtra("name", getGroupName());
        startActivity(intent);
    }
}